package com.yeqian.controller;

import cn.hutool.core.date.DateTime;
import com.yeqian.entity.PageResult;
import com.yeqian.entity.QueryPageBean;
import com.yeqian.entity.Result;
import com.yeqian.pojo.Article;
import com.yeqian.pojo.Tag;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author : yeqian
 * @Date : 2020/12/24 23:08
 * 文章控制器
 */
@RestController
@RequestMapping("/article")
@Api("文章控制器")
public class ArticleController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(ArticleController.class);

    @PutMapping("/top/{id}")
    @ApiOperation("修改置顶的文章")
    public Result updateArticleAndRealaTionShip(@PathVariable("id") Integer articleId){
        articleService.updateArticleAndRealaTionShip(articleId);
        return new Result(true, "获取数据");
    }

    /**
     * 折线图
     *
     * @param
     * @return com.yeqian.entity.Result
     * @author yeqian
     * @date 2021/1/16 22:50
     */
    @PostMapping("/getLineReport")
    @ApiOperation("文章数量增长")
    public Result getLineReport() {
        /*
        格式：两个list集合
        * [820, 932, 901, 934, 1290, 1330, 1320]
        * ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        * */
        //查询各标签占比
   /*     Map<String,Object> list = new HashMap<>();
        List<Object> slist1 = new ArrayList<>();
        List<Object> slist2 = new ArrayList<>();
        slist1.add(82);
        slist1.add(83);
        slist1.add(85);
        slist1.add(72);

        slist2.add("2020/1/1");
        slist2.add("2020/1/2");
        slist2.add("2020/1/3");
        slist2.add("2020/1/4");
        list.put("number",slist1);
        list.put("months",slist2);*/

        Map<String, Object> map = new HashMap<>();

        Calendar instance = Calendar.getInstance();//获得日历对象
        //计算过去一年的12个月
        instance.add(Calendar.MONTH, -12);
        List<String> monthsList = new ArrayList<>();
        List<Integer> articleCountList = new ArrayList<>();
        Date month = null;
        String format = null;
        for (int i = 0; i < 12; i++) {
            instance.add(Calendar.MONTH, 1);
            month = instance.getTime();
            format = new SimpleDateFormat("yyyy.MM").format(month);
            monthsList.add(format);

            Integer articleCount = articleService.getArticleCountByMonth(month);
            articleCountList.add(articleCount);
        }

        map.put("months", monthsList);
        map.put("articleCount", articleCountList);

        return new Result(true, "获取数据", map);
    }

    /**
     * 根据标签分类
     *
     * @param name
     * @return com.yeqian.entity.Result
     * @author yeqian
     * @date 2021/1/16 18:07
     */
    @PostMapping("/getArticleByTagId/{name}")
    @ApiOperation("根据标签分类")
    public Result getArticleByTagId(@PathVariable("name") String name) {
        List<Article> articleByTagId = articleService.getArticleByTagId(name);
        return new Result(true, "根据标签分类成功", articleByTagId);
    }

    /**
     * 查询最近几篇文章
     *
     * @return
     */
    @GetMapping("/getRecent")
    public Result<Article> getRecent() {
        List<Article> articles = articleService.getRecent(5);
        return new Result(true, "查询最近几篇文章成功", articles);
    }

    /**
     * 查询浏览最多次数的文章
     *
     * @param
     * @return com.yeqian.entity.Result<com.yeqian.pojo.Article>
     * @author yeqian
     * @date 2021/1/14 21:01
     */
    @GetMapping("/listOrderByReadCount")
    public Result<Article> listOrderByReadCount() {
        List<Article> articles = articleService.listOrderByReadCount(5);
        return new Result(true, "查询浏览最多次数的文章成功", articles);
    }

    /**
     * 查询所有人的文章记录
     *
     * @param queryPageBean
     * @return com.yeqian.entity.Result<com.yeqian.pojo.Article>
     * @author yeqian
     * @date 2020/12/28 22:20
     */
    @PostMapping("/searchAll")
    public Result<Article> getAllArticleByPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult page = articleService.getAllArticleByPage(queryPageBean);
        return new Result(true, "查询所有人文章成功", page);
    }

    /**
     * 查询最近n条文章记录
     *
     * @param
     * @return
     * @author yeqian
     * @date 2020/12/28 15:22
     */
    @PostMapping("/getRecentArticle/{author}/{start}/{end}")
    @ApiOperation("查询最近n条文章记录")
    public Result getRecentArticle(@PathVariable("author") Integer author, @PathVariable("start") Integer start, @PathVariable("end") Integer end) {
        Map map = new HashMap();
        map.put("author", author);
        map.put("start", start);
        map.put("end", end);
        List<Article> recentArticle = articleService.getRecentArticle(map);
        return new Result(true, "查询最近" + (end - start) + "条文章记录成功", recentArticle);
    }

    /**
     * 获取文章阅读量
     *
     * @param author
     * @return com.yeqian.entity.Result
     * @author yeqian
     * @date 2020/12/28 14:08
     */
    @GetMapping("/getReadCount/{author}")
    @ApiOperation("获取文章阅读量")
    public Result getReadCount(@PathVariable("author") Integer author) {
        Integer readCount = articleService.getReadCount(author);
        return new Result(true, "获取文章阅读量成功", readCount);
    }

    /**
     * 根据文章状态获取 ${当前用户} 文章数量
     *
     * @param
     * @return com.yeqian.entity.Result
     * @author yeqian
     * @date 2020/12/27 23:12
     */
    @GetMapping({"/getTotalCount/{id}/{author}", "/getTotalCount/{author}"})
    public Result getTotalCount(@PathVariable(value = "id", required = false) Integer id, @PathVariable("author") Integer author) {
        Integer totalCount = articleService.getTotalCount(id, author);
        return new Result(true, "获取文章数量成功", totalCount);
    }

    /**
     * 根据主键设置博客状态
     *
     * @param id
     * @return com.yeqian.entity.Result
     * @author yeqian
     * @date 2020/12/27 16:31
     * axios.put("/setStatus/" + row.id,this.formInline).then((res) => {
     */
    @PutMapping("/setStatus/{id}/{status}")
    @ApiOperation("根据主键设置博客状态")
    public Result setStatus(@PathVariable("id") Integer id, @PathVariable("status") Integer status) {
        articleService.setStatus(id, status);
        return new Result(true, "设置回收站成功");
    }

    /**
     * 根据主键修改文章成功
     *
     * @param id
     * @return com.yeqian.entity.Result
     * @author yeqian
     * @date 2020/12/25 0:14
     */
    @PutMapping({"/{id}", "/{id}/{Tags}"})
    @ApiOperation("根据主键修改文章")
    public Result updateArticle(@PathVariable("id") Integer id, @RequestBody Article article, @PathVariable(name = "Tags", required = false) String[] Tags) {
        if (Tags != null) {
            saveArticleTag(Tags, article);
        }
        String Introduce = isIntroduce(article.getContent());
        Article articleId = article.setId(id);
        article.setIntroduce(Introduce);
        article.setRecentEdit(new DateTime());
        articleService.updateArticle(articleId);
        return new Result(true, "根据主键修改文章成功");
    }


    /**
     * 根据主键删除文章成功
     *
     * @param id
     * @return com.yeqian.entity.Result
     * @author yeqian
     * @date 2020/12/25 0:08
     */
    @DeleteMapping("/{id}")
    @ApiOperation("根据主键删除文章成功")
    public Result deleteArticle(@PathVariable("id") Integer id) {
        articleService.deleteArticle(id);

        return new Result(true, "根据主键删除文章成功");
    }


    /**
     * 根据主键获取查询文章
     *
     * @param id
     * @return com.yeqian.entity.Result
     * @author yeqian
     * @date 2020/12/25 0:05
     */
    @GetMapping("/{id}")
    @ApiOperation("根据主键获取查询文章")
    public Result getArticle(@PathVariable("id") Integer id) {
        Article article = articleService.getArticle(id);
        //logger.error("【查询文章】");
        return new Result(true, "根据主键获取查询文章成功", article);
    }

    /**
     * 文章的分页查询，查询状态码为发布状态0的文章
     *
     * @param
     * @return com.yeqian.entity.Result
     * @author yeqian
     * @date 2020/12/24 23:17
     */
    @PostMapping("/search/{statusCode}")
    @ApiOperation("文章的分页查询")
    public Result listQueryPage(@RequestBody QueryPageBean queryPageBean, @PathVariable("statusCode") Integer status) {
        PageResult pageResult = articleService.listQueryPage(queryPageBean, status);
        return new Result(true, "查询成功", pageResult);
    }

    /**
     * 添加文章
     *
     * @param article
     * @return com.yeqian.entity.Result
     * @author yeqian
     * @date 2020/12/24 23:16
     */
    @PostMapping({"/", "{Tags}"})
    @ApiOperation("添加文章")
    public Result saveArticle(@RequestBody Article article, @PathVariable(name = "Tags", required = false) String[] Tags) {
        if (Tags != null) {
            saveArticleTag(Tags, article);
        }
        article.setRecentEdit(new DateTime());
        article.setPublishTime(new DateTime());
        String Introduce = isIntroduce(article.getContent());
        article.setIntroduce(Introduce);
        article.setStatus(0);//0代表发布状态
        articleService.saveArticle(article);
        return new Result(true, "添加成功");
    }

    /**
     * 设置文章的标签
     *
     * @param Tags
     * @param article
     * @return void
     * @author yeqian
     * @date 2021/1/1 22:33
     */
    public void saveArticleTag(String[] Tags, Article article) {
        List<Tag> tags = new ArrayList<>();
        for (String tagname : Tags) {
            Tag tag = new Tag();
            tag.setName(tagname);
            tags.add(tag);
        }
        article.setTags(tags);
    }

    /**
     * 确定最后截取的文章介绍
     * 当正文不过10位时，截取全部
     * 超过10位，截取前10位，遇上# 符号改为空格
     *
     * @param
     * @return boolean
     * @author yeqian
     * @date 2020/12/27 12:09
     */
    public String isIntroduce(String content) {
        String Introduce = null;
        if (content.length() < 10) {
            int length = content.length();
            Introduce = content.substring(0, length).replaceAll("#", "") + "...";
        } else {
            Introduce = content.substring(0, 10).replaceAll("#", "") + "...";
        }
        return Introduce;
    }
}
